package com.xxl.shoppingapp.http;


import com.loopj.android.http.AsyncHttpResponseHandler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxl.baselib.util.LogUtil;

import cz.msebera.android.httpclient.Header;

/**
 * Title: ResponseHandler.java
 * Description:
 * Copyright (c) 版权所有请勿抄袭 2018
 * Created DateTime: 2018/4/9 15:00
 * Created by xuelianx.
 */
public class ResponseHandler extends AsyncHttpResponseHandler {

    private ResponseListener listener;

    public ResponseHandler(ResponseListener listener) {
        this.listener = listener;
    }

    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        String responseString = new String(responseBody);
        if (responseString.isEmpty()) return;
        LogUtil.xxlLog().d("responseString:" + responseString);
        JSONObject object = JSON.parseObject(responseString);
        String code = object.getString("code");
        String data = object.getString("data");
        listener.onFinish();
        if (code.equals("200")) {
            listener.onSuccess(data);
        } else {
            listener.onFailed(code + " " + object.getString("msg") + "\n");
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        LogUtil.xxlLog().d("errorMessage:" + statusCode + "===" + error.getMessage());
        listener.onFinish();
        listener.onFailed(statusCode + " " + error.getMessage() + "\n");
    }

}
